package pl.edu.uj.tcs.blef.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public final class TableListener extends Thread {
	private ServerSocket socket;
	private Table table;
	private boolean running;
	private int TABLE_CONNECTIONS;
	
	public void decrementConnections(){
		if(TABLE_CONNECTIONS > 0) TABLE_CONNECTIONS--;
	}
	
	void terminate(){
		this.running = false;
		this.TABLE_CONNECTIONS = Integer.MAX_VALUE;
	}
	
	@Override
	public void run(){
		while(this.running){
			while(TABLE_CONNECTIONS <= GlobalSettings._MAX_TABLE_CONNECTIONS_){
				try {
					Socket s = socket.accept();
					TABLE_CONNECTIONS++;
					System.out.println("New incoming client connection at table " + socket.getLocalPort() + "...");
					new TableConnectionHandler(table, s);
				} catch (IOException e) { System.out.println("Socket closed."); }
			}
		}
	}
	
	public TableListener(Table table, ServerSocket socket){
		this.socket = socket;
		this.table = table;
		this.running = true;
		start();
	}
}